package com.regex.web.filter;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

public class SearchQueryFilter {

	public enum Operator {
		EQ, NEQ, LIKE, GT, LT, GTE, LTE, IN,BET,DET,OR,NE,NS,BETL,LIKEP,LIKES
	}

	public String fieldName;
	public Object value;
	public Operator operator;

	public SearchQueryFilter(String fieldName, Operator operator, Object value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	/**
	 * searchParams中key的格式为OPERATOR_FIELDNAME
	 */
	public static Map<String, SearchQueryFilter> parse(Map<String, Object> searchParams) {
		Map<String, SearchQueryFilter> filters = new HashMap<String, SearchQueryFilter>();

		for (Entry<String, Object> entry : searchParams.entrySet()) {
			// 过滤掉空值
			String key = entry.getKey();
			Object value = entry.getValue();
			/*if (StringUtils.isBlank((String) value)) {
				continue;
			}*/

			// 拆分operator与filedAttribute
			String[] names = StringUtils.split(key, "_");
			if (names.length != 2) {
				throw new IllegalArgumentException(key + " is not a valid search filter name");
			}
			String filedName = names[1];
			Operator operator = Operator.valueOf(names[0]);

			// 创建searchFilter
			SearchQueryFilter filter = new SearchQueryFilter(filedName, operator, value);
			filters.put(key, filter);
		}

		return filters;
	}

	@Override
	public String toString() {
		return "SearchQueryFilter [fieldName=" + fieldName + ", value=" + value
				+ ", operator=" + operator + "]";
	}
}
